package bancosys.tec.utils.reader;

import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * @author takeshi
 */
public class JARURLReader implements URLReader {

    /**
     * {@inheritDoc}
     * 
     * @see bancosys.tec.utils.reader.URLReader#getFiles(java.net.URL, java.lang.String)
     */
    public List<URL> getFiles(URL root, String pattern) throws IOException {
        List<URL> files = new ArrayList<URL>();

        JarURLConnection jarUrlConnection = (JarURLConnection) root.openConnection();
        jarUrlConnection.connect();
        JarEntry jarEntry = jarUrlConnection.getJarEntry();
        JarFile jarFile = jarUrlConnection.getJarFile();
        Enumeration<JarEntry> entries = jarFile.entries();

        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            if (!entry.isDirectory() && entry.getName().startsWith(jarEntry.getName()) && entry.getName().matches(pattern)) {
                files.add(new URL("jar:file:" + jarFile.getName() + "!/" + entry.getName()));
            }
        }

        return files;
    }
}
